﻿using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using KinonekoSoftware.Drawings;
using KinonekoSoftware.Platform.Windows;

namespace KinonekoSoftware.Studio
{
    public static class SnapshotHelper
    {
        public static readonly DependencyProperty EnableSnapshotProperty = DependencyProperty.RegisterAttached(
                                                                                            "ShadowEnableSnapshot",
                                                                                            typeof(bool),
                                                                                            typeof(SnapshotHelper),
                                                                                            new PropertyMetadata(default(bool)));

        public static void SetEnableSnapshot(DependencyObject element, bool value)
        {
            if (element is Border border)
            {
                border.MouseLeftButtonDown += OnScreenshot;
            }
            
            element.SetValue(EnableSnapshotProperty, value);
        }

        public static bool GetEnableSnapshot(DependencyObject element)
        {
            return (bool)element.GetValue(EnableSnapshotProperty);
        }

        private static async void OnScreenshot(object sender, MouseButtonEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed && e.ClickCount > 1 && sender is Border Container)
            {
                var ms      = Snapshot.CaptureToStream(Container, 125);
                var opendlg = Shell.Save(Shell.PngFilter, Shell.PngExt);

                if (opendlg.ShowDialog() != true)
                {
                    return;
                }

                await File.WriteAllBytesAsync(opendlg.FileName, ms.ToArray());
            }
        }
    }
}